#define _CRT_SECURE_NO_WARNINGS 1

#include"SLT.h"

void SLTprint(SLTnode* phead)
{
	if (phead == NULL)
	{
		printf("NULL");
	}
	else
	{
		SLTnode* tmp = phead;
		while (tmp)
		{
			printf("%d->", tmp->data);
			tmp = tmp->next;
		}
		printf("NULL\n");
	}
}

SLTnode* SLTbuynode(SLTdatatype x)
{
	SLTnode* tmp = (SLTnode*)malloc(sizeof(SLTnode));
	tmp->data = x;
	tmp->next = NULL;
	return tmp;
}


void SLTPushback(SLTnode** pphead, SLTdatatype x)
{
	assert(pphead);
	if (*pphead == NULL)
	{
		SLTnode* p = SLTbuynode(x);
		*pphead = p;

	}
	else
	{
		SLTnode* tmp = *pphead;
		SLTnode* p = SLTbuynode(x);
		while (tmp->next)
		{
			tmp = tmp->next;
		}
		tmp->next = p;
	}
}

void SLTPushFront(SLTnode** pphead, SLTdatatype x)
{
	assert(pphead);
	
	SLTnode* p = SLTbuynode(x);
	p->next = *pphead;
	*pphead = p;

	
}

void SLTPopback(SLTnode** pphead)
{
	assert(pphead);
	assert(*pphead);
	if ((*pphead)->next==NULL)
	{
		SLTnode* tmp = *pphead;
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTnode* prev = NULL;
		SLTnode* tmp = *pphead;
		while (tmp->next)
		{
			prev = tmp;
			tmp = tmp->next;
		}
		prev->next = NULL;
		free(tmp);
		tmp = NULL;
	

	}

	
}

void SLTPopfront(SLTnode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLTnode* tmp = *pphead;
	*pphead = (*pphead)->next;
	free(tmp);
}

SLTnode* SLTfind(SLTnode* phead, SLTdatatype x)
{
	SLTnode* tmp = phead;
	while (tmp)
	{
		if (tmp->data == x)
		{
			return tmp;
		}
		tmp = tmp->next;
	}

	return NULL;
}

void SLTinsert(SLTnode** pphead, SLTnode* pos, SLTdatatype x)
{
	assert(pphead);
	assert(pos);

	if (pos == *pphead)
	{
		SLTPushFront(pphead,x);
	}
	else
	{
		SLTnode* tmp=SLTbuynode(x);
		SLTnode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = tmp;
		tmp->next = pos;

	}

}


void SLTinsertafter(SLTnode** pphead, SLTnode* pos, SLTdatatype x)
{
	assert(pphead);
	assert(pos);
	assert(*pphead);
	SLTnode* p = SLTbuynode(x);
	p->next = pos->next;
	pos->next = p;



}


void SLTerase(SLTnode** pphead, SLTnode* pos)
{
	assert(pphead);
	assert(pos);
	if (pos==*pphead)
	{
		SLTnode* tmp = *pphead;
		*pphead = (*pphead)->next;
		free(tmp);
	}
	else
	{
		SLTnode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}


		prev->next = pos->next;
		free(pos);
	}

}

void SLTeraseafter(SLTnode* pos)
{
	assert(pos);
	assert(pos->next);
	SLTnode* tmp = pos->next;
	pos->next = pos->next->next;
	free(tmp);
}


void SLTdestroy(SLTnode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLTnode* tmp = *pphead;
	while (tmp)
	{
		SLTnode* next = tmp->next;
		free(tmp);
		tmp = next;

		
	}
	*pphead = NULL;
}







